package czk.concrent.juc.cyclicbarrier.practice;

import java.util.concurrent.*;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/7/21 22:38
 */
public class CyclicBarrierPra {
    static String order1 = null;
    static String order2 = null;
    static String order3 = null;
    static String order4 = null;
    static String[] orders = {"红烧肉", "小炒肉", "宫保鸡丁", "水煮肉", "夫妻肺片", "狮子头", "沸腾鱼"};

    public static void main(String[] args) {
        CyclicBarrier cyclicBarrier = new CyclicBarrier(4, () -> {
            System.out.println("先生们所点的菜是" + order());
        });
        // 创建线程组
        ExecutorService threadPool = Executors.newFixedThreadPool(4);
        for (int i = 0; i < 4; i++) {
            threadPool.execute(() -> {
                // 随机暂停
                try {
                    TimeUnit.MILLISECONDS.sleep(ThreadLocalRandom.current().nextLong(1000L));
                    order1 = orders[ThreadLocalRandom.current().nextInt(orders.length)];
                    cyclicBarrier.await();
                } catch (Exception e) {
                    e.printStackTrace();
                }

            });
            threadPool.execute(() -> {
                // 随机暂停
                try {
                    TimeUnit.MILLISECONDS.sleep(ThreadLocalRandom.current().nextLong(1000L));
                    order2 = orders[ThreadLocalRandom.current().nextInt(orders.length)];
                    cyclicBarrier.await();
                } catch (Exception e) {
                    e.printStackTrace();
                }

            });
            threadPool.execute(() -> {
                // 随机暂停
                try {
                    TimeUnit.MILLISECONDS.sleep(ThreadLocalRandom.current().nextLong(1000L));
                    order3 = orders[ThreadLocalRandom.current().nextInt(orders.length)];
                    cyclicBarrier.await();
                } catch (Exception e) {
                    e.printStackTrace();
                }

            });
            threadPool.execute(() -> {
                // 随机暂停
                try {
                    TimeUnit.MILLISECONDS.sleep(ThreadLocalRandom.current().nextLong(1000L));
                    order4 = orders[ThreadLocalRandom.current().nextInt(orders.length)];
                    cyclicBarrier.await();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        }
    }

    private static String order() {
        return order1+"===="+order2+"===="+order3+"===="+order4;
    }
}
